import 'package:mvvm_provider/base/base_state.dart';
import 'package:mvvm_provider/model/banner_model.dart';
import 'package:mvvm_provider/page/bookshelf/states/book_shelf_state.dart';
import '../../../base/base_view_model.dart';
import '../../../config/handle_state.dart';
import '../../../model/response_model.dart';
import '../../../net/ltt_https.dart';
import '../../../net/http_config.dart';
import '../../home/model/cartoon_model.dart';

class BookShelfViewModel extends BaseViewModel {

  BookShelfState state = BookShelfState();

  /// 获取列表数据
  Future<void> getListData(String url, String bannerUrl,int number) async {
    if (url == '') {
      /// 没有更多数据了
      refreshController.refreshCompleted();
      refreshController.loadComplete();
      refreshController.loadNoData();

      state.netState = NetState.dataSuccessState;
      notifyListeners();
      return;
    }

    if (number == 1) {
      ResponseModel? bannerResponseModel =
          await LttHttp().request<List<BannerModel>>(bannerUrl, method: HttpConfig.get);
      state.bannerList = bannerResponseModel.data;
    }

    ResponseModel? responseModel =
        await LttHttp().request<CarDataModel>(url, method: HttpConfig.get);
    CarDataModel carDataModel = responseModel.data;

    /// 处理页面状态
    state.netState = HandleState.handle(responseModel, successCode: 0);
    if (state.netState == NetState.dataSuccessState) {
      if (number == 1) {
        state.dataList = handleData(carDataModel.feeds ?? []);
        if (state.dataList.isEmpty) {
          state.netState = NetState.emptyDataState;
        }
      } else {
        state.dataList.addAll(carDataModel.feeds ?? []);
        state.dataList = handleData(state.dataList);

        /// 显示没有更多数据了
        if (state.dataList.isEmpty) {
          refreshController.loadNoData();
        }
      }
      refreshController.refreshCompleted();
      refreshController.loadComplete();
    }
    notifyListeners();
  }

  /// 处理数据
  List handleData(List list) {
    for (int i = 0; i < list.length; i++) {
      CartoonModel cartoonModel = list[i];
      if (i % 3 == 0) {
        cartoonModel.crossAxisCount = 2;
      } else {
        cartoonModel.crossAxisCount = 1;
      }
    }
    return list;
  }
}
